<template>
  <div class="login-from">
    <el-tabs v-model="loginType" class="demo-tabs">
      <el-tab-pane label="密码登录" name="account">
        <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入账号/手机号">
              <template #prefix>
                <el-icon class="el-input__icon">
                  <user />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              show-password
              autocomplete="new-password"
            >
              <template #prefix>
                <el-icon class="el-input__icon">
                  <lock />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <!-- <el-tab-pane label="验证码登录" name="phone">
        <el-form ref="phoneFormRef" :model="phoneForm" :rules="phoneFormRules" size="large">
          <el-form-item prop="mobile">
            <el-input v-model="phoneForm.mobile" placeholder="请输入手机号码" :maxlength="11">
              <template #prefix>
                <el-icon class="el-input__icon">
                  <Iphone />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="validCode">
            <el-row type="flex" justify="space-around" style="width: 100%">
              <el-col :span="16">
                <el-input
                  v-model.number="phoneForm.validCode"
                  oninput="if(value.length>6)value=value.slice(0,6)"
                  :disabled="phoneForm.mobile.length < 11"
                  placeholder="请输入验证码"
                  autocomplete="off"
                  :maxlength="6"
                >
                </el-input>
              </el-col>
              <el-col :span="8" style="text-align: right">
                <el-button @click="sendVerifyCode" :disabled="state.txtVerifyCode != '获取验证码'">{{
                  state.txtVerifyCode
                }}</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-tab-pane> -->
    </el-tabs>

    <div class="login-btn">
      <el-button size="large" type="primary" :loading="loading" @click="login()">
        {{ $t("common.login") }}
      </el-button>
    </div>
    <el-button style="float: right" link type="primary" href="#" @click="showDialog">忘记密码?</el-button>
    <!-- <Verify
      mode="pop"
      :captcha-type="'blockPuzzle'"
      :img-size="{ width: '400px', height: '200px' }"
      ref="verifyRef"
      @success="handleSuccess"
    ></Verify> -->
    <forget-dialog type="password" ref="forgetRef"></forget-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
import { ElNotification } from "element-plus";
import { SystemApi } from "@/api/modules";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, Iphone, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";

import { PLATFORM } from "@/config";
import { checkPhoneNumber } from "@/utils/eleValidate";
import forgetDialog from "./forgetDialog.vue";
import { SmsSceneEnum } from "@/enums/httpEnum";

import Verify from "@/components/verifition/Verify.vue";
import Cookies from "js-cookie";
const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const phoneFormRef = ref<FormInstance>();
const verifyRef = ref<InstanceType<typeof Verify>>();
const loginRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});
const phoneFormRules = {
  mobile: [
    { required: true, message: "请输入手机号" },
    {
      validator: checkPhoneNumber,
    },
  ],
  validCode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
};
const loginType = ref("account");
const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  username: "",
  password: "",
  platform_type: PLATFORM,
  captchaVerification: "",
});
const phoneForm = reactive<Login.PhoneLoginForm>({
  mobile: "",
  validCode: "",
  captchaVerification: "",
});

const state = reactive({
  codeLoginDisabled: true,
  second: 60,
  txtVerifyCode: "获取验证码",
  codeData: {
    text: "获取验证码",
    disabled: false,
  },
});
const handleSuccess = param => {
  console.log(param, 144);
  if (loginType.value == "account") {
    loginForm.captchaVerification = param.captchaVerification || "";
    login();
  } else {
    phoneForm.captchaVerification = param.captchaVerification || "";
    login();
  }
};
const countdown = () => {
  if (state.second == 0) {
    state.txtVerifyCode = "获取验证码";
    state.second = 60;
  } else {
    state.txtVerifyCode = `${state.second}s 重新获取`;
    state.second--;
    setTimeout(() => {
      countdown();
    }, 1000);
  }
};

const sendVerifyCode = () => {
  phoneFormRef.value.validateField(["mobile"], valid => {
    if (!valid) return;
    const params = {
      scene: SmsSceneEnum.LOGIN,
      mobile: phoneForm.mobile,
      captchaVerification: phoneForm.captchaVerification,
    };
    SystemApi.sendSmsCode(params)
      .then(res => {
        state.codeLoginDisabled = false;
        countdown();
      })
      .catch(err => {
        if (err.code == 602) {
          verifyRef.value.show();
        }
      })
      .finally(() => {
        phoneForm.captchaVerification = "";
      });
  });
};
const loginByPwd = () => {
  loginFormRef.value.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口

      const params = {
        ...loginForm,
      };
      const { data } = await SystemApi.loginApi(params);
      localStorage.clear();
      Cookies.remove("loginToken");
      userStore.setToken(data.access_token);
      // 2.添加动态路由
      await initDynamicRouter();
      // 3.清空 tabs、keepAlive 数据
      tabsStore.closeMultipleTab();
      keepAliveStore.setKeepAliveName();
      // 4.跳转到首页
      if (userStore.permissionInfo.user.needUpdatePwd) {
        router.push({
          path: "/updatePwd",
        });
      } else {
        router.push(HOME_URL);
        ElNotification({
          title: getTimeState(),
          message: "欢迎登录",
          type: "success",
          duration: 3000,
        });
      }
    } catch (err) {
      if (err.code == 602) {
        verifyRef.value.show();
      }
    } finally {
      loginForm.captchaVerification = "";
      loading.value = false;
    }
  });
};
const loginByPhone = () => {
  phoneFormRef.value.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口

      const params = {
        grant_type: "password",
        client_id: "xinwei",
        client_secret: 123456,
        scope: "all",
        type: "SMS",
        username: phoneForm.mobile,
        password: phoneForm.validCode,
        captchaVerification: phoneForm.captchaVerification,
        platform_type: PLATFORM,
      };
      const { data } = await loginApi(params);
      userStore.setToken(data.access_token);
      // 2.添加动态路由
      await initDynamicRouter();
      // 3.清空 tabs、keepAlive 数据
      tabsStore.closeMultipleTab();
      keepAliveStore.setKeepAliveName();
      // 4.跳转到首页

      if (userStore.permissionInfo.user.needUpdatePwd) {
        router.push({
          path: "/updatePwd",
        });
      } else {
        router.push(HOME_URL);
        ElNotification({
          title: getTimeState(),
          message: "欢迎登录",
          type: "success",
          duration: 3000,
        });
      }
    } catch (err) {
      if (err.code == 602) {
        verifyRef.value.show();
      }
    } finally {
      loginForm.captchaVerification = "";
      loading.value = false;
    }
  });
};
// login
const login = () => {
  if (!loginFormRef.value) return;
  switch (loginType.value) {
    case "account":
      loginByPwd();
      break;
    case "phone":
      loginByPhone();
      break;
  }
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const forgetRef = ref<InstanceType<typeof forgetDialog> | null>(null);
const showDialog = () => {
  forgetRef.value.openDialog();
};

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login();
    }
  };
});
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
